<?php
// Usage:
//   php tools/device_tcp/util/extract_photo.php <log_path> [--mid=1] [--out=tools/device_tcp/tmp/photo.jpg]
// Finds the latest getUserRsp line for the given mid in the log, extracts data.photo (base64),
// decodes it and writes a JPEG to the output path.

if ($argc < 2) {
    fwrite(STDERR, "Usage: php extract_photo.php <log_path> [--mid=1] [--out=output.jpg]\n");
    exit(1);
}

$logPath = $argv[1];
$mid = null;
$out = null;
foreach (array_slice($argv, 2) as $arg) {
    if (strpos($arg, '--mid=') === 0) {
        $mid = intval(substr($arg, 6));
    } elseif (strpos($arg, '--out=') === 0) {
        $out = substr($arg, 6);
    }
}
if (!is_file($logPath)) {
    fwrite(STDERR, "Log file not found: {$logPath}\n");
    exit(1);
}

$latestJson = null;
$latestLine = '';
$fp = fopen($logPath, 'r');
while (($line = fgets($fp)) !== false) {
    if (strpos($line, 'getUserRsp') !== false && strpos($line, 'json=') !== false) {
        $pos = strpos($line, 'json=');
        if ($pos !== false) {
            $jsonStr = substr($line, $pos + 5); // after 'json='
            $jsonStr = trim($jsonStr);
            // Some logs may end with trailing characters, but usually it's the pure JSON
            $parsed = json_decode($jsonStr, true);
            if (is_array($parsed) && isset($parsed['data'])) {
                if ($mid === null || intval($parsed['data']['mid'] ?? 0) === $mid) {
                    $latestJson = $parsed;
                    $latestLine = $line;
                }
            }
        }
    }
}
fclose($fp);

if (!$latestJson) {
    fwrite(STDERR, "No getUserRsp JSON found for mid=" . ($mid ?? 'ANY') . " in log.\n");
    exit(2);
}

$photoB64 = strval($latestJson['data']['photo'] ?? '');
if ($photoB64 === '') {
    fwrite(STDERR, "Found getUserRsp but data.photo is empty.\n");
    exit(3);
}

$raw = base64_decode($photoB64, true);
if ($raw === false) {
    fwrite(STDERR, "Failed to base64_decode photo.\n");
    exit(4);
}

if ($out === null || $out === '') {
    $ts = date('Ymd_His');
    $midStr = strval($latestJson['data']['mid'] ?? 'x');
    $out = __DIR__ . '/../tmp/photo_mid' . $midStr . '_' . $ts . '.jpg';
}
$dir = dirname($out);
if (!is_dir($dir)) @mkdir($dir, 0777, true);

file_put_contents($out, $raw);

$size = strlen($raw);
$imgInfo = @getimagesizefromstring($raw);
$wh = $imgInfo ? ($imgInfo[0] . 'x' . $imgInfo[1]) : 'unknown';

echo "Saved photo to: {$out}\n";

echo "Photo bytes: {$size}, dimensions: {$wh}\n";

echo "Log line: \n{$latestLine}\n";

